package com.amigo.online.provider.adv.interceptor;

import java.lang.reflect.Method;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.amigo.online.common.base.security.LocalUser;
import com.amigo.online.common.core.response.StatusCode;
import com.amigo.online.common.core.security.IgnoreSecurity;
import com.amigo.online.common.util.StringUtils;
import com.amigo.online.provider.adv.exception.TokenException;
import com.amigo.online.provider.adv.service.TokenManagerService;

/**
 * token拦截器
 *
 * @author amigo
 */
@Component
public class TokenInterceptor extends HandlerInterceptorAdapter {
    private static final Logger logger = LoggerFactory.getLogger(TokenInterceptor.class);

    @Resource
    private TokenManagerService tokenManagerService;

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        LocalUser.removeUser();
        super.afterCompletion(request, response, handler, ex);
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        super.afterConcurrentHandlingStarted(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        //  Auto-generated method stub
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        logger.debug("Method:" + method.getName() + ", IgnoreSecurity: " + method.isAnnotationPresent(IgnoreSecurity.class));
        logger.debug("request path: " + request.getRequestURI());

        if (method.isAnnotationPresent(IgnoreSecurity.class)) {
            return true;
        }
        String token = request.getHeader("ACCESS_TOKEN");
        if (token == null || StringUtils.isEmpty(token)) {
            token = request.getParameter("access_token");
        }
        if (token == null || StringUtils.isEmpty(token)) {
            throw new TokenException(StatusCode.UNAUTHORIZED);
        }
        // 检查 token 有效性
        if (!tokenManagerService.checkToken(token)) {
            throw new TokenException(StatusCode.UNAUTHORIZED);
        }
        return true;
    }
}
